package com.eboss.sbs.activity;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

import com.eboss.sbs.R;
import com.eboss.sbs.activity.base.BaseActivity;
import com.eboss.sbs.activity.base.MainTabActivity;
import com.eboss.sbs.config.Config;
import com.eboss.sbs.enums.EnumConsts;
import com.eboss.sbs.http.API;
import com.eboss.sbs.http.HttpCallback;
import com.eboss.sbs.model.ActivateSubmitEntity;
import com.eboss.sbs.model.LoginEntity;
import com.google.gson.reflect.TypeToken;
import com.mytools.tool.security.Base64;
import com.mytools.tool.utils.LocalParasUtils;
import com.mytools.tool.utils.StringUtil;
import com.mytools.tool.views.MyDialog;
import com.wosai.upay.bean.UpayOrder.PayModel;
import com.wosai.upay.bean.UpayResult;
import com.wosai.upay.common.DebugConfig;
import com.wosai.upay.common.UpayCallBack;
import com.wosai.upay.common.UpayTask;
import com.wosai.upay.http.Env;

import java.util.HashMap;
import java.util.Map;

public class LoginActivity extends BaseActivity {

	public static String LOGIN_USERNAME = "LOGIN_USERNAME";
	public static String LOGIN_PASSWORD = "LOGIN_PASSWORD";
	
	private UpayTask upayTask;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		mActivity = this;
		isImmersiveNotification = false;
	    setContentView(R.layout.activity_login);
		super.onCreate(savedInstanceState);
		initView();
		showImmersiveNotification(this);
		initSqbSDK();
	}
	
	private void initSqbSDK() {
		upayTask = UpayTask.getInstance();
		DebugConfig.setDebug(true);//默认为非调试模式,如果需要调试,请设置为 true,打印和保存相关日志
		upayTask.initUpay(this, true, Env.UrlType.PRO);
	}
	
	private void showImmersiveNotification(Activity context){
		//if(mContext==null)return;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {  
        	((Activity) context).getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//        	context.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
	}
	
	private void openDialog(){
		MyDialog.Builder builder = new MyDialog.Builder(this);
		builder.setTitle("忘记密码");
		builder.setMessage("请联系管理员索取密码，或拨打400电话咨询客服人员");
		builder.setPositiveButton("呼叫400电话", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				//拨号界面
				Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"+ Config.TEL_CONTACT));
	            startActivity(intent);  
			}
		});
		builder.setNegativeButton("知道了",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		builder.create().show();
	}

	private void initView(){
		findViewById(R.id.btn_login).setOnClickListener(this);
		findViewById(R.id.btn_forget_password).setOnClickListener(this);
		
		String username = mApp.shareUtil.getShareStringPara(LOGIN_USERNAME, "");
		if(!StringUtil.isNull(username)){
			setTvEnable(R.id.tv_username, false);
			setTvText(R.id.tv_username, username);
		}
		else setTvEnable(R.id.tv_username, true);
		
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.btn_login:
				login();
				break;
			case R.id.btn_forget_password:
				openDialog();
				break;
			default: break;
		}
		super.onClick(v);
	}
	
	private void login(){
		String username = getTvText(R.id.tv_username);
		String password = getTvText(R.id.tv_password);
		if(StringUtil.isNull(username)){toast("用户名不能为空！");return;}
		else if(StringUtil.isNull(password)){toast("密码不能为空！");return;}
		login_request(username, password);
	}
	
	private void login_request(final String username, final String password){
		LocalParasUtils.removeXLoginFlag(mActivity);
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("userName", username);
		params.put("password", Base64.getBase64(password));
		
		TelephonyManager tm = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE); 
		String imei = tm.getDeviceId();
		params.put("terminalSn", imei);
		
		API.http_post(this, API.LOGON, params, new HttpCallback<LoginEntity>(this) {
			
			@Override
			public void onSuccess(int statusCode, LoginEntity data) {
				
				mApp.setLoginEntity(data);
				
				mApp.shareUtil.setShareStringPara(LOGIN_USERNAME, username); //保存登录UserName
				mApp.shareUtil.setShareStringPara(LOGIN_PASSWORD, password); //保存登录UserName
				
				LocalParasUtils.saveXLoginDate(mActivity);	//设置最后登录时间
				
				//当返回扫码支付方式是富友时，不再进行激活处理
				int scanPayType = data.getScanPayType();
				if(scanPayType== EnumConsts.ScanPayType.FUYOU.getType()){
					gotoMainPage();
					finish();
					return;
				}
				
				boolean hasActivated = LocalParasUtils.checkActivateStatus(mActivity);
				String xActivityCode = LocalParasUtils.getActivateCode(mActivity);
				String nActivityCode = data.getActivateCode();
				
				if(hasActivated&&!StringUtil.isNull(nActivityCode)&&nActivityCode.equals(xActivityCode)){
					//System.out.println("激活码： "+PayChannelChooseActivity.getActivateCode(mActivity));
					gotoMainPage();
				}
				else{
					if(StringUtil.isNull(nActivityCode)){gotoMainPage();}
					else{
						LocalParasUtils.removeActivateStatus(mActivity);
						activite(nActivityCode);
					}
				}
			}
			
			@Override
			public void onFailure(int statusCode, String message) {
				mApp.shareUtil.removeSharePara(LOGIN_PASSWORD);
				super.onFailure(statusCode, message);
			}
			
			@SuppressWarnings({ "unchecked", "rawtypes" })
			@Override
			public TypeToken getTypeToken() {
				return new TypeToken<LoginEntity>() {
				};
			}
		});
	}
	
	/**
	 * 激活终端
	 * @param code
	 */
	private void activite(final String code){
		String vendor_id = "";//服务商 ID
		String vendor_key = "";//服务商 KEY
		try {
			ApplicationInfo appInfo = this.getPackageManager().getApplicationInfo(getPackageName(),PackageManager.GET_META_DATA);
			vendor_id = appInfo.metaData.getString("com.sqb.vendor_id");
			vendor_key = appInfo.metaData.getString("com.sqb.vendor_key");
		} catch (Exception e) {
			Toast.makeText(this, "未配置收钱吧ID与KEY", Toast.LENGTH_SHORT).show();
		}
		
		/**
		* activate 激活
		* @param code 激活码
		* @param vendor_id 服务商 ID
		* @param vendor_key 服务商 KEY 
		* @param payModel 支付模式
		* @param callBack 请求回调
		*/
		upayTask.activate(code, vendor_id, vendor_key, PayModel.NO_UI, new UpayCallBack() {
			@Override
			public void onExecuteResult(UpayResult result) {
				String RESULT_CODE = result.getResult_code();
				if(!StringUtil.isNull(RESULT_CODE)&&RESULT_CODE.equals("ACTIVATE_SUCCESS")){
					//Toast.makeText(LoginActivity.this, "激活成功！！", Toast.LENGTH_SHORT).show();
					submit_after_actvate(code, 1);
				}
				else{
					LocalParasUtils.removeActivateStatus(LoginActivity.this);
					//Toast.makeText(LoginActivity.this, "终端激活失败，请联系客服！", Toast.LENGTH_SHORT).show();
					submit_after_actvate(code, 0);
					//gotoMainPage();
				}
			}
		});
	}
	
	/**
	 * 向服务器返回激活结果
	 * @param code	激活码
	 * @param isSuccess	0失败  1成功
	 */
	private void submit_after_actvate(final String code, final int isSuccess){
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("sid", mApp.getLoginEntity().getSid());
		params.put("activateCode", code);
		params.put("isSuccess", isSuccess);
		API.http_post(this, API.ACTIVATE_SUBMIT, params, new HttpCallback<ActivateSubmitEntity>(this, false) {
			@Override
			public void onSuccess(int statusCode, ActivateSubmitEntity data) {
				LocalParasUtils.removeActivateStatus(mActivity);
				if(isSuccess==1){
					LocalParasUtils.saveActivateCode(mActivity, code);
					LocalParasUtils.saveMerchantNo(mActivity, data.getMerchantNo());
					LocalParasUtils.saveMerchantName(mActivity, data.getMerchantName());
					LocalParasUtils.saveTerminalName(mActivity, data.getTerminalName());
				}
				gotoMainPage();
			}
			@Override
			public void onFailure(int statusCode, String message) {
				LocalParasUtils.removeActivateStatus(mActivity);
				gotoMainPage();
				super.onFailure(statusCode, message);
			}
			@SuppressWarnings({ "unchecked", "rawtypes" })
			@Override
			public TypeToken getTypeToken() {
				return new TypeToken<ActivateSubmitEntity>() {};
			}
		});
	}
	
	private void gotoMainPage(){
		startActivity(new Intent(mActivity, MainTabActivity.class));
		finish();
	}
	
}
